package com.hejing.线程安全问题;

/**
 * ClassName: WindowTest
 * Package: com.hejing.线程安全问题
 * Description:
 *      使用实现Runnable的方式，实现卖票
 *      加上同步方法以解决线程安全问题
 * @Author: HeJing
 * @Create: 2023-04-14 19:21
 * @Version: 1.0
 */
public class WindowWithSynchronizedFuncTest {
    public static void main(String[] args) {

        SaleTicketWithSynFunc s1 = new SaleTicketWithSynFunc();
        Thread t1 = new Thread(s1);
        Thread t2 = new Thread(s1);
        Thread t3 = new Thread(s1);

        t1.setName("窗口1");
        t2.setName("窗口2");
        t3.setName("窗口3");

        t1.start();
        t2.start();
        t3.start();
    }
}

class SaleTicketWithSynFunc implements Runnable {
    int ticket = 100;
    boolean isFlag = true;

    /**
     *  对于非静态方法，同步监视器默认是 "this"
     *  对于静态方法，同步监视器默认是 "当前类.class"
     */

    public synchronized void synFuncTest() {  // 此时的同步监视器默认是 : this
        if(ticket > 0) {
            System.out.println(Thread.currentThread().getName() + "售票, 票号为: " + (101 - ticket));
            ticket--;
        } else {
            isFlag = false;
        }
    }

    @Override
    public void run() {
        while(isFlag) {
            synFuncTest();
        }
    }
}
























